package org.mineground.commands.irc;

import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import java.io.File;
import org.jibble.pircbot.Colors;
import org.jibble.pircbot.User;
import org.mineground.Main;
import org.mineground.handlers.irc.CommandExecutor;
import org.mineground.handlers.irc.UserLevel;

/**
 * @name IPLocation.java
 * @author Daniel Koenen (2012)
 */
public class IPLocation implements CommandExecutor {
    @Override
    public void onCommand(User sender, UserLevel level, String channel, String command, String arguments[]) {
        if (level.compareTo(UserLevel.IRC_OP) < 0) {
	    return;
        }

        if (arguments.length < 1) {
            Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Usage:" + Colors.NORMAL + " !iplocation [ip-address]");
	    return;
	}
        
        String ipAddress = arguments[0];
        
        if (!ipAddress.matches("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b")) {
            Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Usage:" + Colors.NORMAL + " !iplocation [ip-address]");
            return;
        }
        
        try {
            LookupService lookupService = new LookupService(new File(Main.getInstance().getDataFolder(), "GeoLiteCity.dat"));
            Location ipLocation = lookupService.getLocation(ipAddress);
            
            if (ipLocation == null) {
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Error: No result found.");
                return;
            }

            StringBuilder locationBuilder = new StringBuilder();
            locationBuilder.append(Colors.TEAL);
            locationBuilder.append("* Location info for IP \"");
            locationBuilder.append(ipAddress);
            locationBuilder.append("\"");
            locationBuilder.append(Colors.NORMAL);
            locationBuilder.append(": Country: ");
            locationBuilder.append(((ipLocation.countryName == null) ? ("Unknown") : (ipLocation.countryName)));
            locationBuilder.append(", City: ");
            locationBuilder.append(((ipLocation.city == null) ? ("Unknown") : (ipLocation.city)));
            Main.getInstance().getIRCHandler().sendMessage(channel, locationBuilder.toString());
        }
        
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
